package com.gnerv.cms.service.impl;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gnerv.cms.dto.CatalogDTO;
import com.gnerv.cms.dto.CatalogSaveDTO;
import com.gnerv.cms.dto.CatalogSearchDTO;
import com.gnerv.cms.dto.CatalogTreeDTO;
import com.gnerv.cms.entity.Catalog;
import com.gnerv.cms.mapper.CatalogMapper;
import com.gnerv.cms.mapper.SiteMapper;
import com.gnerv.cms.service.ICatalogService;
import com.gnerv.cms.utils.UUIDUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.List;

@Slf4j
@Service
public class CatalogServiceImpl extends ServiceImpl<CatalogMapper, Catalog> implements ICatalogService {

    @Resource
    SiteMapper siteMapper;

    @Resource
    CatalogMapper catalogMapper;

    @Override
    public boolean saveCatalog(CatalogSaveDTO catalogSaveDTO) {
        if(StringUtils.isEmpty(catalogSaveDTO.getUkId())){
            createCatalog(catalogSaveDTO);
        }else {
            updateCatalog(catalogSaveDTO);
        }
        return true;
    }

    @Override
    public boolean createCatalog(CatalogSaveDTO catalogSaveDTO) {
        Catalog catalog = catalogSaveDTO.convert();
        catalog.setUkId(UUIDUtils.getLower());
        catalogMapper.insert(catalog);
        siteMapper.bindSiteCatalog(catalogSaveDTO.getSiteId(), catalog.getUkId());
        return true;
    }

    @Override
    public boolean deleteByCatalogId(String catalogId) {
        catalogMapper.deleteById(catalogId);
        siteMapper.unBindSiteCatalog(catalogId);
        return true;
    }

    @Override
    public boolean updateCatalog(CatalogSaveDTO catalogSaveDTO) {
        Catalog catalog = catalogSaveDTO.convert();
        catalogMapper.updateById(catalog);
        siteMapper.unBindSiteCatalog(catalog.getUkId());
        siteMapper.bindSiteCatalog(catalogSaveDTO.getSiteId(), catalog.getUkId());
        return true;
    }

    @Override
    public boolean updateCatalogStatus(String catalogId, Integer status) {
        catalogMapper.updateCatalogStatus(catalogId, status);
        return true;
    }

    @Override
    public CatalogDTO selectCatalog(String catalogId) {
        CatalogDTO catalog = catalogMapper.selectCatalog(catalogId);
        return catalog;
    }

    @Override
    public Page<CatalogDTO> listCatalog(CatalogSearchDTO catalog, Long current, Long size) {
        Page<CatalogDTO> catalogs = catalogMapper.listCatalog(new Page<CatalogDTO>(current, size), catalog);
        return catalogs;
    }

    @Override
    public List<CatalogTreeDTO> listCatalogTree(CatalogSearchDTO catalog) {
        return catalogMapper.listCatalogTree(catalog);
    }
}
